package com.jxb.network;


import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.jxb.dialog.utils.ProgressDialogUtils;
import com.lzy.okgo.callback.AbsCallback;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Response;

/**
 * @author jinxb
 * date     : 2021/7/13
 * desc     :
 */
public abstract class BaseJsonCallback<T extends BaseResponseBean> extends AbsCallback<T> {
    private UnPeekLiveData<String> errorMsgLiveData;

    public BaseJsonCallback(UnPeekLiveData<String> errorMsgLiveData) {
        this.errorMsgLiveData = errorMsgLiveData;
    }

    @Override
    public void onSuccess(com.lzy.okgo.model.Response<T> response) {
        T body = response.body();
        if (body == null) {
            onError(response);
            return;
        }
        if (body.isSuccess()) {
            onSuccess(body);
        } else {
            onError(response.code(), body.getErrorMsg());
        }
    }


    @Override
    public void onError(com.lzy.okgo.model.Response<T> response) {
        super.onError(response);
        try {
            assert response.getRawResponse().body() != null;
            onError(response.code(), response.getRawResponse().body().string());
        } catch (IOException e) {
            onError(response.code(), response.getRawResponse().message());
        }
    }

    @Override
    public void onFinish() {
        super.onFinish();
        ProgressDialogUtils.dismissProgressDialog();
    }

    @Override
    public T convertResponse(Response response) {
        if (response.isSuccessful()) {
            if (response.body() == null) {
                return null;
            }
            T data = null;
            Gson gson = new Gson();
            JsonReader jsonReader = new JsonReader(response.body().charStream());
            Type genType = getClass().getGenericSuperclass();
            assert genType != null;
            Type type = ((ParameterizedType) genType).getActualTypeArguments()[0];
            data = gson.fromJson(jsonReader, type);
            return data;
        }
        return null;
    }


    protected void onError(int code, String errorMsg) {
        errorMsgLiveData.postValue("接口异常：" + errorMsg);
    }

    protected abstract void onSuccess(T body);
}

